package cn.dengta.context.web;

import java.util.List;

import cn.dengta.common.context.Env;
import cn.dengta.common.util.Common;
import me.codeplayer.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 在入参时，对 图片进行压缩与CDN处理
 *
 * @see ImageConverter#convert(String)
 */
public class ImageConverter implements Converter<String, String> {

	public static final String CDN = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // https://oss.flala6.com";
	public static final String CDN_INCHAT = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // "https://oss.guangxijunxuan.cn";

	public static final String CDN_TEST = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // "https://test-flala.oss-cn-shenzhen.aliyuncs.com";
	public static final String CDN_INCHAT_TEST = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // "https://test-liaoyu.oss-cn-shenzhen.aliyuncs.com";
	/** OSS压缩后缀 */
	public static final String COMPRESS_SUFFIX = "!dt";
	/** 覆盖的域名 */
	public static final String COVER_DOMAIN = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // "https://prod-hkflala.oss-cn-hongkong.aliyuncs.com";
	/** inchat */
	public static final String COVER_INCHAT_DOMAIN = "https://inchat0.oss-cn-hongkong.aliyuncs.com"; // "https://prod-liaoyu.oss-cn-shenzhen.aliyuncs.com";

	@Override
	public String convert(String source) {
		boolean replaceCdn;
		if (StringUtil.notEmpty(source) && ((replaceCdn = (Env.inProduction() && (source.startsWith(COVER_INCHAT_DOMAIN) || source.startsWith(COVER_DOMAIN)))))) {
			List<String> paths = Common.splitAsStringList(source);
			if (paths != null) {
				StringBuilder sb = new StringBuilder(source.length());
				boolean first = false;
				for (String path : paths) {
					if (first) {
						sb.append(Common.SEP);
					} else {
						first = true;
					}
					sb.append(replaceCdn ? path.replace(COVER_INCHAT_DOMAIN, CDN_INCHAT).replace(COVER_DOMAIN, CDN) : path);
					final String suffix = StringUtils.substringAfterLast(path, ".");
					if (StringUtil.notEmpty(suffix) && suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")) {
						sb.append(COMPRESS_SUFFIX);
					}
				}
				return sb.toString();
			}
		}
		return source;
	}

	public static String getCdnDomain(boolean isInterior) {
		if (Env.inProduction()) {
			return isInterior ? CDN_INCHAT : CDN;
		} else {
			return isInterior ? CDN_INCHAT_TEST : CDN_TEST;
		}
	}

}
